package com.abc.recycling.service.impl;

import com.abc.recycling.domain.Evaluation;
import com.abc.recycling.repository.EvaluationRepository;
import com.abc.recycling.service.EvaluationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Optional;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class EvaluationServiceImpl implements EvaluationService {

    private final EvaluationRepository evaluationRepository;

    @Override
    public Evaluation getEvaluation(Long id) {
        return evaluationRepository.findById(id).orElse(null);
    }

    @Override
    public List<Evaluation> getUserEvaluations(Long userId) {
        return evaluationRepository.findByUserId(userId);
    }

    @Override
    public List<Evaluation> getCollectorEvaluations(Long collectorId) {
        return evaluationRepository.findByCollectorId(collectorId);
    }

    @Override
    public List<Evaluation> getCollectorRecentEvaluations(Long collectorId, int limit) {
        return evaluationRepository.findByCollectorIdOrderByCreateTimeDesc(collectorId, limit);
    }

    @Override
    public Double getCollectorAverageRating(Long collectorId) {
        try {
            return evaluationRepository.getAverageRatingByCollectorId(collectorId);
        } catch (Exception e) {
            log.error("获取回收员平均评分失败: {}", e.getMessage());
            return 0.0;
        }
    }

    @Override
    public List<Integer> getCollectorRatingDistribution(Long collectorId) {
        try {
            List<Integer> distribution = new ArrayList<>();
            // 获取1-5星的评价数量
            for (int i = 1; i <= 5; i++) {
                int count = (int) evaluationRepository.countByCollectorIdAndRating(collectorId, i);
                distribution.add(count);
            }
            return distribution;
        } catch (Exception e) {
            log.error("获取回收员评分分布失败: {}", e.getMessage());
            // 返回全0的分布
            return Arrays.asList(0, 0, 0, 0, 0);
        }
    }

    @Override
    public long getCollectorEvaluationCount(Long collectorId) {
        try {
            return evaluationRepository.countByCollectorId(collectorId);
        } catch (Exception e) {
            log.error("获取回收员评价数量失败: {}", e.getMessage());
            return 0;
        }
    }

    @Override
    public long getCollectorNewEvaluationCount(Long collectorId) {
        return evaluationRepository.countByCollectorIdAndCreateTimeAfter(collectorId, LocalDateTime.now().minusDays(7));
    }

    @Override
    public boolean isOrderEvaluated(Long orderId) {
        return evaluationRepository.existsByOrderId(orderId);
    }

    @Override
    @Transactional
    public Evaluation createEvaluation(Evaluation evaluation) {
        evaluation.setCreateTime(LocalDateTime.now());
        evaluation.setUpdateTime(LocalDateTime.now());
        return evaluationRepository.save(evaluation);
    }

    @Override
    @Transactional
    public void updateEvaluation(Evaluation evaluation) {
        evaluation.setUpdateTime(LocalDateTime.now());
        evaluationRepository.update(evaluation);
    }

    @Override
    @Transactional
    public void deleteEvaluation(Long id) {
        evaluationRepository.deleteById(id);
    }

    @Override
    @Transactional
    public Evaluation replyEvaluation(Long id, String reply) {
        Optional<Evaluation> optionalEvaluation = evaluationRepository.findById(id);
        if (!optionalEvaluation.isPresent()) {
            throw new RuntimeException("评价不存在");    
        }
        Evaluation evaluation = optionalEvaluation.get();
        evaluation.setReply(reply);
        evaluation.setReplyTime(LocalDateTime.now());
        evaluation.setUpdateTime(LocalDateTime.now());
        evaluationRepository.update(evaluation);
        return evaluation;
    }

    @Override
    public List<Evaluation> searchEvaluations(Long userId, Long collectorId, Integer status, Double minRating, Double maxRating) {
        return evaluationRepository.searchEvaluations(userId, collectorId, status, minRating, maxRating);
    }
}